<template>
    <el-form :inline="true" size="large">
        <el-form-item label="视频名称">
            <el-input v-model="formData.videoTitle" placeholder="请输入视频名称" clearable @clear="refreshPage" style="width: 250px;"></el-input>
        </el-form-item>
        <el-form-item label="视频名称">
          <el-select v-model="formData.courseId" clearable @clear="refreshPage" placeholder="请选择课程名" style="width: 240px">
              <el-option v-for="item in classList" :key="item.id" :label="item.courseName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="getAllComm">搜索</el-button>
            <el-button type="primary" @click="adddate">新增视频</el-button>
            <el-button type="danger" @click="removeBatch">批量删除</el-button>
        </el-form-item>
    </el-form>
    <el-form>
        <el-table :data="visitList" border class="my-table" size="large" @selection-change="handleSelectionChange">
            <el-table-column type="selection" :selectable="selectable" width="55" />
            <el-table-column prop="id" label="ID" align="center"></el-table-column>
            <el-table-column prop="videoTitle" label="视频名称" align="center"></el-table-column>
            <el-table-column prop="videoTime" label="视频时长" align="center"></el-table-column>
            <el-table-column prop="videoUrl" label="视频" align="center" width="300">
              <template v-slot="scope">
                  <video controls width="300" height="100" :src="`http://localhost:8081/sfzy${scope.row.videoUrl}`"></video>
              </template>
            </el-table-column>
            <el-table-column prop="course.courseName" label="课程名称" align="center"></el-table-column>
            <el-table-column prop="del" label="状态" align="center">
                <template v-slot="scope">  
                    <span :class="{c1:scope.row.del==0,c2:scope.row.del==1}">{{ scope.row.del == 0 ? '正常' : '删除' }}</span>  
                </template> 
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template v-slot="scope">
                    <el-link type="primary" @click="updata(scope.row)">修改</el-link>
                    <el-link type="danger" @click="handleDownshelf(scope.row)">删除</el-link>
                </template>
            </el-table-column>
        </el-table>
    </el-form>
    <el-dialog v-model="dialogFormVisible" :title="title" width="525" @close="cancel">
        <el-form :model="adddate" class="form1">
            <el-form-item label="视频名称" :label-width="formLabelWidth">
                <el-input v-model="visitData.videoTitle" autocomplete="off" />
            </el-form-item>
            <el-form-item label="视频" :label-width="formLabelWidth">
              <el-upload ref="upload" class="upload-demo" action="http://localhost:8081/sfzy/uploadVideo"
                  :limit="1" :on-exceed="handleExceed" :auto-upload="false" :on-success="handleAvatarSuccess">
                  <template #trigger>
                    <el-button type="primary" style="width: 100px;">select file</el-button>
                  </template><br>
                  <el-button type="success" @click="submitUpload" style="width: 100px;">upload file</el-button>
                  <template #tip>
                    <div class="el-upload__tip text-red">{{tip}}</div>
                  </template>
              </el-upload>
            </el-form-item>
            <el-form-item label="课程名称" :label-width="formLabelWidth">
              <el-select v-model="visitData.courseId" clearable @clear="refreshPage" placeholder="请选择分类名" style="width: 240px">
                  <el-option v-for="item in classList1" :key="item.id" :label="item.courseName" :value="item.id" />
              </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :disabled="!fileUploaded">确定</el-button>
            </div>
        </template>
  </el-dialog>
  <el-row>
      <el-pagination
        :page-sizes="[5, 10, 30, 40]"
        :size="size"
        :disabled="disabled"
        :background="background"
        :default-page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="pageNumChange"
      />
    </el-row>
  </template>
  
  <script setup>
  //icon图标
  import { Search,Refresh,Edit,CloseBold,Plus,Share,ArrowRight  } from '@element-plus/icons-vue'
  //信息提示
  import { ElForm, ElMessage, ElMessageBox, uploadProps } from 'element-plus';
  //getCurrentInstance获取全局对象，用于获取axios属性
  //onMounted页面加载后开始挂载执行
  //watchEffect属性监听器，daterange响应后开始执行函数，这里用于获取开始时间和结束时间
  import { getCurrentInstance, onMounted, ref, watchEffect,onBeforeUnmount } from 'vue';
  //接收全局对象
  const CurrentInstance=getCurrentInstance()
  //初始化添加弹框，使其不显示
  const dialogFormVisible = ref(false)
  //添加弹出框左边距
  const formLabelWidth = '140px'
  //获取全局对象挂载的naxios赋值给$http来代替naxios
  const {$http}=CurrentInstance.appContext.config.globalProperties
  //弹出框的标题
  const title=ref("")
  //代表active样式
  const i=ref("")
  //默认动态页码为0
  const total=ref(0)
  //课程id和课程名
  const classList = ref([]);
  const classList1 = ref([]);
  //视频地址中转
  const imageUrl = ref('')
  const imgUrl=ref('')
  const tip=ref("请上传并提交一个文件")
   // 初始化为false，表示文件还未上传成功
  const fileUploaded = ref(false);
  //动态方法，默认弹出框为add
  const operationType = ref('add');
  //定义formData来接收访问地址的数据
  const formData =ref({
    videoTitle:"",
    courseId:"",
    pageNum:1 ,// 页码
    pageSize:5, // 每页展示条数
    ids:[]//多选id
  })
  //定义的表格数据来存放访问地址中的数据
  let visitList=ref([
    
  ])
  let visitData=ref({
    id:"",
    videoTitle:"",
    videoTime:"",
    videoUrl:"",
    courseId:"",
    del:""
  })
  //监听函数，if else是为了防止访问空时报错，同时获取页面的开始时间和结束时间
  watchEffect(function(){
    
  })
  //点击搜索的清除组件，刷新页面
  function refreshPage() {
      getAllComm();
  }
  //生命周期中挂载到页面加载之后开始执行
  onMounted(()=>{
    getAllComm()
    getListComm()
  })
  //获取点击的分页页码并执行搜索功能
  function pageNumChange(num){
      formData.value.pageNum=num;
      getAllComm()
  }
  function handleSizeChange(size){
      formData.value.pageSize=size;
      getAllComm()
  }
  //文件上传
  const upload = ref(null)
  
  const handleExceed = (files) => {
    upload.value.clearFiles()
    const file = files[0]
    upload.value.handleStart(file)
  }
  
  const submitUpload = () => {
    upload.value.submit()
  }
  const handleAvatarSuccess = (response, uploadFile) => {
      // 保存返回的视频时长,并转换为时分秒
      visitData.value.videoTime = response.data.duration;
      // 保存相对路径到相关数据对象，以便传给后端
      const relativeImagePath = response.data.videoPath;
      // 拼接完整的图片路径在弹出框中显示
      const fullImagePath = `http://localhost:8081/sfzy${relativeImagePath}`;
      imageUrl.value = URL.createObjectURL(uploadFile.raw);
      imgUrl.value = fullImagePath
  
      //传回数据库的路径
      visitData.value.videoUrl = relativeImagePath;
      fileUploaded.value = true; // 文件上传成功，更新状态为true
  };
  //搜索功能，将formData的定义初始属性传给访问地址，并传回来地址中的表格数据和各个属性
  function getAllComm(){
    $http({
        method:"get",
        url:"http://localhost:8081/sfzy/courseVideo/page",
        params:formData.value
    }).then(res=>{ 
        visitList.value=res.data.data.list;//获取访问地址中的列表数据传给visitList
        const list = res.data.data.list;
        list.forEach(item => {
              const seconds = Math.floor(item.videoTime / 1000);
              item.videoTime = formatTime(seconds);
          });
        total.value=res.data.data.total;
    })
  }
  function getListComm() {
      $http({
          method: "get",
          url: "http://localhost:8081/sfzy/course"
      }).then(res => {
          classList.value = res.data.data;
          classList1.value = res.data.data       
      })
  }
  // 新增分类函数
  function addNewCategory() {
      $http({
          method: "post",
          url: "http://localhost:8081/sfzy/courseVideo",
          data: visitData.value
      }).then(res => {
          if (res.data.code === 200) {
              ElMessage.success("添加成功！");
          } else {
              ElMessage.error("添加失败");
          }
          dialogFormVisible.value = false;
          getAllComm();
          cancel();
      });
  }
  // 使添加框显示（新增分类）
  function adddate() {
      dialogFormVisible.value = true;
      title.value = "新增视频";
      operationType.value ='add';
      // 初始化相关数据（可根据实际需求补充更多初始化操作）
      visitData.value = {
        id:"",
        videoTitle:"",
        videoTime:"",
        videoUrl:"",
        courseId:"",
        del:""
      };
      // 重置文件上传组件状态，清除已选择的文件
      if (upload.value) {
          upload.value.clearFiles();
      }
      fileUploaded.value = false; // 添加这行代码，将fileUploaded重置为false，使确定按钮初始为禁用状态
  }
  // 修改分类函数
  function updateCategory(val) {
      console.log('val.videoTime:', val.videoTime); // 添加这行代码用于查看传入参数的值和类型
      // 将时分秒格式的视频时长转换回毫秒值
      val.videoTime = formatTime(Math.floor(val.videoTime / 1000));
      val.videoTime = convertTimeToMilliseconds(val.videoTime);
      console.log(val.videoTime);
      $http({
          method: "put",
          url: "http://localhost:8081/sfzy/courseVideo",
          data: val
      }).then(res => {
          if (res.data.code === 200) {
              ElMessage.success("修改成功！");
          } else {
              ElMessage.error("修改失败");
          }
          dialogFormVisible.value = false;
          getAllComm();
          cancel();
      });
  }
  // 点击修改链接弹出修改框并执行修改操作
  function updata(val) {
      dialogFormVisible.value = true;
      title.value = "修改课程";
      visitData.value = val;
      const fileUrl = `http://localhost:8081/sfzy${val.videoUrl}`;
      if (fileUrl) {
          // 将文件路径赋值给对应的用于显示等用途的变量，比如imageUrl等，这里以imageUrl为例
          imageUrl.value = fileUrl;  
          tip.value="已有视频，可重新上传并覆盖"
          fileUploaded.value = true;
      }
      operationType.value ='modify';
  }
  // 新增一个函数用于将时分秒格式转换回毫秒值，例如 "00:01:00" 转换为 60000（1分钟对应的毫秒数）
  function convertTimeToMilliseconds(timeStr) {
      const [hours, minutes, seconds] = timeStr.split(':').map(Number);
      return (hours * 3600 + minutes * 60 + seconds) * 1000;
  }
  // 统一提交函数，根据操作类型调用相应函数
  function handleSubmit() {
      if (operationType.value === 'add') {
          addNewCategory();
      } else if (operationType.value ==='modify') {
          updateCategory(visitData.value);
      }
      // 重置文件上传组件状态，清除已选择的文件
  }
  //删除功能
  function handleDownshelf(val){
      if (formData.value.ids.length > 0) {
          ElMessage({
              type: 'warning',
              message: '已选择了多行，请使用批量删除功能进行操作！',
          });
          return;
      }
      ElMessageBox.confirm(
      '是否确认删除小区数据?',
      '删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        const { id } = val;
        $http({
            method:"delete",
            url:`http://localhost:8081/sfzy/courseVideo/${id}`,
            data:{}
        }).then(res=>{
            if (res.data.code === 200) {  
                ElMessage.success("删除成功！");  
            } else {  
                ElMessage.error("删除失败");  
            }  
            getAllComm(); 
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除操作',
        })
      })
  }
  //批量删除
  const selectable = (row) => ![].includes(row.id)
  const handleSelectionChange = (val) => {
    formData.value.ids = val.map(item => item.id);
  }
  function removeBatch(){
      ElMessageBox.confirm(
      '是否确认删除小区数据?',
      '删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        const idsArray  = formData.value.ids;
        // 将数组idsArray中的元素拼接成字符串形式，用逗号分隔
        const idsStr = idsArray.join(',');
        
        $http({
            method:"delete",
            url:`http://localhost:8081/sfzy/courseVideo?ids=${idsStr}`,
            data:{}
        }).then(res=>{
            if (res.data.code === 200) {  
                ElMessage.success("删除成功！");  
                // 判断当前页是否还有数据，如果没有则将页码减1
                  if (visitList.value.length === 0 && formData.value.pageNum > 1) {
                      formData.value.pageNum--;
                  }
                  // 清理ids参数
                  formData.value.ids = [];
            } else {  
                ElMessage.error("删除失败");  
            }  
            getAllComm(); 
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除操作',
        })
      })
  }
  // 时间格式转换函数，用于将秒数转换为时分秒格式
  function formatTime(seconds) {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const remainingSeconds = seconds % 60;
      return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
  }
  //重置添加输入框内容
  function cancel(){
    dialogFormVisible.value = false;
    tip.value="请上传并提交一个文件"
    visitData.value = {
      id:"",
      videoTitle:"",
      videoTime:"",
      videoUrl:"",
      courseId:"",
      del:""
    }
    getAllComm()
  }
  
  </script>
    
  <style scoped>
    .demo-form-inline .el-input {--el-input-width: 220px;}
    .demo-form-inline .el-select {--el-select-width: 220px;}
    .el-link {padding: 0 5px;}
    .el-form{width: 1420px;}
    .el-input{width: 300px;}
    .form1{width: 100%;}
    .el-pagination{margin-top: 25px;}
    .coordinates{margin-left: 10px;}
    .my-table :deep(th){background-color: #1890ff;color: #ffffff;text-align: center;}
    .mendian{margin-bottom: 15px;}
    .active{color: green;}
    .avatar{
        width: 250px;
        height: 220px;
        display: block;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }
  
    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }
  
    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 250px;
        height: 178px;
        text-align: center;
    }
    .c1{color: #1890ff;cursor: pointer;}
    .c2{color: red;cursor: pointer;}
    .table-img {
      width: 100px; /* 根据需要调整图片宽度 */
      height: 100px; /* 根据需要调整图片高度 */
      object-fit: cover; /* 控制图片如何填充容器，cover会保持图片比例并填满容器 */
  }
  </style>